  
package com.xebest.web.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xebest.common.util.XeBaseUtil;
import com.xebest.util.SysSetBeanUtils;
import com.xebest.web.form.XeVenAreaRoleForm;
import com.xebest.web.mapper.write.XeVenAreaRoleWriteMapper;
import com.xebest.web.model.XeVenAreaRoleEntity;
import com.xebest.web.service.XeVenAreaRoleService;
import com.xebest.web.view.XeVenAreaRoleView;
import com.xebest.web.view.XeVenAreaView;

@Service
public class XeVenAreaRoleServiceImpl implements XeVenAreaRoleService {

    private static final Logger log = LoggerFactory.getLogger(XeVenAreaRoleServiceImpl.class);//日志记录类

    @Autowired
    private XeVenAreaRoleWriteMapper xeVenAreaRoleWriteMapper; //区域权限角色权限业务操作
	
	

    /**
     * 批量插入角色区域权限信息
     * @author: 李贝贝
     * @createTime: 2017年6月17日 下午12:18:37  
     * @history:  
     * @param list
     * @return int
     * @modifyTime : 2017年9月7号 杜春静
     * 修改内容：角色区域修改
     */
     @Transactional(value="writeTransactionManager")
     public  Map<String, Object> insertAreaRole(XeVenAreaRoleForm form) throws Exception{

    	 Map<String, Object> resultMap = new HashMap<String, Object>();
    	 //区域数组
    	 String[] areaArray = form.getAreaIdArr();
    	 //要添加的区域角色列表
    	 List<XeVenAreaRoleEntity> paramEntites = new ArrayList<XeVenAreaRoleEntity>();
    	 int result = 0;
    	 
    	 if(null != areaArray && areaArray.length > 0){
    		
    		 for(String areaId : areaArray){
    			if(StringUtils.isEmpty(areaId)){
    				continue;
    			}
    			//封装区域角色实体
    			XeVenAreaRoleEntity areaRoleEntity = new XeVenAreaRoleEntity();
    			areaRoleEntity.setAreaId(Integer.valueOf(areaId));
    			areaRoleEntity.setRoleId(form.getRoleId());
    			areaRoleEntity.setUserCode(form.getUserCode());
    			//查询区域orgcode
				Integer areaLevel = XeBaseUtil.baseUtil.getAreaLevel(Integer.valueOf(areaId));
				areaRoleEntity.setAreaLevel(areaLevel);

	            //区域orgcode
	            String areaOrgCode = XeBaseUtil.baseUtil.getAreaOrgCode(Integer.valueOf(areaId));
	            areaRoleEntity.setAreaOrgCode(areaOrgCode);
	            
	            paramEntites.add(areaRoleEntity);
	           
    		}
    	}
    	 //先删除原有的区域角色
    	 XeVenAreaRoleEntity areaRoleEntity2 = new XeVenAreaRoleEntity();
    	 areaRoleEntity2.setRoleId(form.getRoleId());
    	 areaRoleEntity2.setUserCode(form.getUserCode());
    	 xeVenAreaRoleWriteMapper.deleteAreaRole(areaRoleEntity2);
    	 
    	 if(null != paramEntites && paramEntites.size() > 0){
    		 //再添加新的区域角色
        	 result = xeVenAreaRoleWriteMapper.insertAreaRole(paramEntites);
    	 }
    	 
    	 resultMap.put("result", String.valueOf(result));
    	 return resultMap;
     }
    

     /**
      * 修改区域角色权限 策略：先删除再添加
      * @author: 李贝贝
      * @createTime: 2017年6月17日 下午2:27:34  
      * @history:  
      * @param AreaRoleForm
      * @return
      * @throws Exception int
      */
     @Transactional(value="writeTransactionManager")
     public  int updateAreaRole(XeVenAreaRoleForm form) throws Exception{
    	 XeVenAreaRoleEntity entity = SysSetBeanUtils.toAreaRoleEntity(form);
    	 log.debug("修改区域角色权限 策略：先删除再添加实体转换为：{}",JSON.toJSONString(entity));
    	 xeVenAreaRoleWriteMapper.deleteAreaRole(entity);//删除角色区域权限权限
    	 List<XeVenAreaRoleEntity> paramEntites = SysSetBeanUtils.toAreaRoleList(form);//转换要保存的角色区域权限权限
    	 log.debug("修改区域角色权限 策略：先删除再添加实体转换为：{}",JSON.toJSONString(paramEntites));
    	 return xeVenAreaRoleWriteMapper.insertAreaRole(paramEntites);
     }


	  
	/* 
	 * 查询角色区域权限 
	 *(non-Javadoc)  
	 * @see com.xebest.web.service.XeVenAreaRoleService#queryRoleArea(com.xebest.web.form.XeVenAreaRoleForm)  
	*/  
	@Override
	public XeVenAreaRoleView queryRoleArea(XeVenAreaRoleForm form) {
		XeVenAreaRoleView areaRoleView = new  XeVenAreaRoleView();
		areaRoleView.setRoleId(form.getRoleId());
		
		 XeVenAreaRoleEntity entity = new XeVenAreaRoleEntity();
		 entity.setRoleId(form.getRoleId());
		 entity.setUserCode(form.getUserCode());
    	
		 log.debug("根据用户标识查找已经分配的角色区域权限实体转换为：{}",JSON.toJSONString(entity));
    	 JSONArray coverAreaArray = new JSONArray();
    	 List<XeVenAreaView> coverAreaList = xeVenAreaRoleWriteMapper.queryAreaRole(entity);
    	 if(null != coverAreaList && coverAreaList.size() >0){
    		 coverAreaArray =queryCoverAreaList(coverAreaList, null);	
    		 //省信息
				Map<String, XeVenAreaView> pMap = new HashMap<>();
				//市信息
				Map<String, XeVenAreaView> cMap = new HashMap<>();
				//区信息
				Map<String, XeVenAreaView> aMap = new HashMap<>();
				Integer areaId;
				Integer pId = 0;
				Integer cId = 0;
				String areaName;
				for(XeVenAreaView areaView : coverAreaList){
					areaName = XeBaseUtil.baseUtil.getAreaName(areaView.getAreaId());
					areaView.setAreaName(areaName);
					areaId = areaView.getAreaId();
					Integer areaLevel = areaView.getAreaLevel();
					if (areaLevel == 1) {
						pMap.put(areaId.toString(), areaView);
					} else if (areaLevel == 2) {
						//2.二级城市,设置父级省城市信息
						cMap.put(areaId.toString(), areaView);
						//获得当前市的省id
						pId = XeBaseUtil.baseUtil.getAreaParentId(areaId);
						//设置省信息
						setAreaInfoByAreaId(pMap, pId);
					} else if (areaLevel == 3) {
						//2.三级城市,设置父级省市的信息
						aMap.put(areaId.toString(), areaView);
						//获得市id
						cId = XeBaseUtil.baseUtil.getAreaParentId(areaId);
						if (cMap.get(cId.toString()) == null) {
							//获得省的市名称
							setAreaInfoByAreaId(cMap, cId);
							//获得市的省id
							pId = XeBaseUtil.baseUtil.getAreaParentId(cId);
							setAreaInfoByAreaId(pMap, pId);
						}
					}
				}
				JSONObject areaArray;
				JSONObject cityArray;
				String areaIdStr;
				JSONObject pSaleArea;
				JSONObject cityArea;
				String cityId;
				XeVenAreaView cArea;
				JSONArray citySaleAreaList;
				JSONArray areaAreaList;
				String aAreaId;
				XeVenAreaView pArea;
				XeVenAreaView aArea;
				for(int i = 0,count = coverAreaArray.size(); i < count; i++){
					areaArray = coverAreaArray.getJSONObject(i);
					areaIdStr = areaArray.getString("areaId");
					pArea = pMap.get(areaIdStr);
					if (pArea != null){
						if (pArea.getAreaId() != null && pArea.getAreaId() != null && pArea.getAreaId() != 0) {
							//省级销售区域id不为空，说明该数据属于省级销售数据
							pSaleArea = JSONObject.parseObject(JSONObject.toJSONString(pArea));

							coverAreaArray.set(i, pSaleArea);
							citySaleAreaList = areaArray.getJSONArray("areaList");
							if(citySaleAreaList != null && citySaleAreaList.size() > 0){
								for (int j = 0; j < citySaleAreaList.size(); j++){
									cityArray = citySaleAreaList.getJSONObject(j);
									cityId = cityArray.getString("areaId");
									cArea = cMap.get(cityId);
									if (cArea != null) {
										if (cArea.getAreaId() != null && cArea.getAreaId() != null && cArea.getAreaId() != 0) {
											cityArea = JSONObject.parseObject(JSONObject.toJSONString(cArea));
											//当前市属于市级销售商品
											citySaleAreaList.set(j, cityArea);
											//当前市下有区级销售商品
											//获得当前市下所有区级城市信息
											areaAreaList = cityArray.getJSONArray("areaList");
											if (areaAreaList != null && areaAreaList.size() > 0) {
												for (int k = 0; k < areaAreaList.size(); k++) {
													aAreaId = areaAreaList.getJSONObject(k).getString("areaId");
													aArea = aMap.get(aAreaId);
													if (aArea != null) {
														JSONObject aAreaJO = JSONObject.parseObject(JSONObject.toJSONString(aArea));
														//区域是否勾选1勾选、2不勾选
														aAreaJO.put("areaCheckBoxFlag", 1);
														areaAreaList.set(k, aAreaJO);
													}
												}
												cityArea.put("areaCheckBoxFlag", 2);
											} else {
												//区域是否勾选1勾选、2不勾选
												cityArea.put("areaCheckBoxFlag", 1);
											}
											//给当前市设置数据
											cityArea.put("areaList", areaAreaList);
										}
									}
								}
								pSaleArea.put("areaCheckBoxFlag", 2);
							} else {
								//区域是否勾选1勾选、2不勾getCoverAreaId选
								pSaleArea.put("areaCheckBoxFlag", 1);
							}
							pSaleArea.put("areaList", citySaleAreaList);
						}
					}
				}
				}
    	 areaRoleView.setAreaList(coverAreaArray);
    	 
    	 return areaRoleView;  
		
	}
	
	/**
	 * 查询区域ID是否在区域Map里，如果没有，则添加
	 * @author: 杜春静  
	 * @createTime: 2017年9月8日 上午11:40:58  
	 * @history:  
	 * @param areaMap
	 * @param areaId void
	 */
	 public void setAreaInfoByAreaId(Map<String, XeVenAreaView> areaMap, Integer areaId) {
	        //设置省信息
	        if (areaMap.get(areaId.toString()) == null) {
	            //获得并设置省名称
	            String areaName = XeBaseUtil.baseUtil.getAreaName(areaId);
	            XeVenAreaView area = new XeVenAreaView();
	            area.setAreaId(areaId);
	            area.setAreaName(areaName);
	            areaMap.put(areaId.toString(), area);
	        }
    }
	 
	 public JSONArray  queryCoverAreaList(List<XeVenAreaView> coverAreaList, Integer areaId){
			
			JSONArray coverAreaArray = new JSONArray();
			if( areaId == null){
				if(!CollectionUtils.isEmpty(coverAreaList)){
						Integer aId;
						Integer areaLevel;
						XeVenAreaView coverAreaEntity;
						//当前角色区域是部分区域，查询指定省信息
						for (int i = 0, len = coverAreaList.size(); i < len; i ++) {
							//根据id获得城市信息
							coverAreaEntity = coverAreaList.get(i);
							aId = coverAreaEntity.getAreaId();
		                    areaLevel = coverAreaEntity.getAreaLevel();
		                	JSONObject areaJson = new JSONObject();
	                    	areaJson.put("areaId", aId);
	                    	areaJson.put("areaName", XeBaseUtil.baseUtil.getAreaName(aId));
	                    	coverAreaArray =coverArrayAddObject(coverAreaArray,areaJson,areaLevel);
		                	
						}
				}
			} else {
	            //查询指定区域id下区域信息
				coverAreaArray = XeBaseUtil.baseUtil.getChildArea(areaId);
	        }
			
			if (!CollectionUtils.isEmpty(coverAreaArray)) {
	            for (int i = 0; i < coverAreaArray.size(); i++) {
	                JSONObject js = coverAreaArray.getJSONObject(i);
	                //区域是否勾选1勾选、2不勾选
	                js.put("areaCheckBoxFlag", 2);
	                JSONArray areaList = js.getJSONArray("areaList");
	                if(null != areaList && areaList.size() > 0){
						 for(int k = 0; k < areaList.size(); k ++){
							 JSONObject cJsonObject = (JSONObject)areaList.get(k);
							 cJsonObject.put("areaCheckBoxFlag", 2);
							 JSONArray aListOld = cJsonObject.getJSONArray("areaList");
							 if(null != aListOld){
								 for(int h = 0; h < aListOld.size(); h ++){
									 JSONObject aJsonObject = (JSONObject)aListOld.get(h);
									 aJsonObject.put("areaCheckBoxFlag", 2);
								 }
							 }
							 
						 }
					 }
	                
	            }
	        }
			return coverAreaArray;
		}
	 
	 
		public JSONArray coverArrayAddObject(JSONArray coverAreaArray, JSONObject pJson, Integer areaLevel){
			//如果区域等级为省
			if(areaLevel == 1){
				for(int j = 0;j < coverAreaArray.size(); j++){
					JSONObject newJsonObjectI = (JSONObject)coverAreaArray.get(j);
					 String  areaIdI = newJsonObjectI.get("areaId").toString();
					 String areaIdJ = pJson.get("areaId").toString();
					 if(areaIdI.equals(areaIdJ)){
						 return coverAreaArray;
					} 
				}
				coverAreaArray.add(pJson);
				 return coverAreaArray;
				
			}
			//如果区域等级为市
			if(areaLevel == 2){
				 String areaIdJ = pJson.get("areaId").toString();
				 Integer pId = XeBaseUtil.baseUtil.getAreaParentId(Integer.valueOf(areaIdJ));
				//如果包含
				 for(int j = 0;j < coverAreaArray.size(); j++){
					 JSONObject newJsonObjectI = (JSONObject)coverAreaArray.get(j);
					 String  areaIdI = newJsonObjectI.get("areaId").toString();
					 if(areaIdI.equals(pId.toString())){
						 JSONArray areaList = newJsonObjectI.getJSONArray("areaList");
						 if( null == areaList){
							 newJsonObjectI.put("areaList", XeBaseUtil.baseUtil.getChildArea(pId));
							 return coverAreaArray;
						 } else {
							 return coverAreaArray;
						 }
					 } 
				}
				//如果不包含
				JSONObject pJson2 = new JSONObject();
	         	pJson2.put("areaId", pId);
	         	pJson2.put("areaName", XeBaseUtil.baseUtil.getAreaName(pId));
	         	pJson2.put("areaList", XeBaseUtil.baseUtil.getChildArea(pId));
	         	coverAreaArray.add(pJson2);
	         	 return coverAreaArray;
			}
			//区域等级为区
			if(areaLevel == 3){
				 String areaIdJ = pJson.get("areaId").toString();
				 //获得区ID
				 Integer aId = Integer.valueOf(areaIdJ);
				 
				 //获得市id
				 Integer cId = XeBaseUtil.baseUtil.getAreaParentId(aId);
				//获得市的省id
				 Integer pId = XeBaseUtil.baseUtil.getAreaParentId(cId);
				 
				 for(int j = 0;j < coverAreaArray.size(); j++){
					 JSONObject newJsonObjectI = (JSONObject)coverAreaArray.get(j);
					 String  areaIdI = newJsonObjectI.get("areaId").toString();
					 //查询是否存在省
					 if(areaIdI.equals(pId.toString())){
						 JSONArray areaList = newJsonObjectI.getJSONArray("areaList");
						 if( null == areaList){
							 JSONArray cList = XeBaseUtil.baseUtil.getChildArea(pId);
							 newJsonObjectI.put("areaList", cList);
							 for(int k = 0; k < cList.size(); k ++){
								 JSONObject cJsonObject = (JSONObject)cList.get(k);
								 String cIdK = cJsonObject.get("areaId").toString();
								 if(cIdK.equals(cId.toString())){
									 JSONArray aList = XeBaseUtil.baseUtil.getChildArea(cId);
									 cJsonObject.put("areaList", aList);
								 }
							 }
							 return coverAreaArray;
						 } else if(null != areaList && areaList.size() > 0){
							 for(int k = 0; k < areaList.size(); k ++){
								 JSONObject cJsonObject = (JSONObject)areaList.get(k);
								 String cIdK = cJsonObject.get("areaId").toString();
								 if(cIdK.equals(cId.toString())){
									 JSONArray aListOld = cJsonObject.getJSONArray("areaList");
									 if(null == aListOld){
										 JSONArray aList = XeBaseUtil.baseUtil.getChildArea(cId);
										 cJsonObject.put("areaList", aList);
									 }
									 
								 }
							 }
							 return coverAreaArray;
						 }
					 }
					 
				 }
				 
				//如果不包含
				JSONObject pJson2 = new JSONObject();
	         	pJson2.put("areaId", pId);
	         	pJson2.put("areaName", XeBaseUtil.baseUtil.getAreaName(pId));
	         	JSONArray cList = XeBaseUtil.baseUtil.getChildArea(pId);
	         	pJson2.put("areaList", cList);
				 for(int k = 0; k < cList.size(); k ++){
					 JSONObject cJsonObject = (JSONObject)cList.get(k);
					 String cIdK = cJsonObject.get("areaId").toString();
					 if(cIdK.equals(cId.toString())){
						 JSONArray aList = XeBaseUtil.baseUtil.getChildArea(cId);
						 cJsonObject.put("areaList", aList);
					 }
				 }
	         	coverAreaArray.add(pJson2);
	         	 return coverAreaArray;
			}
			return coverAreaArray;
		}
}
  
